package org.zzh.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Component;
import org.zzh.domain.system.log.StLog;
import org.zzh.domain.system.user.PeUser;
import org.zzh.service.system.log.StLogService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.UUID;

@Aspect
@Component
@Slf4j
public class LogAspect {

    @Autowired
    HttpSession session;

    @Autowired
    StLogService stLogService;

    @Autowired
    HttpServletRequest request;

    @Pointcut("execution(* org.zzh.controller..*.*(..))")
    public void logPointcut() {
    }

    @Around("logPointcut()")
    public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取用户信息
        PeUser user = (PeUser) session.getAttribute("user");
        if (user == null) {
            user = new PeUser();
            user.setUserName("未登录人员");
            user.setCompanyId("1");
            user.setCompanyName("广州东方标准集团");
        }
        StLog stLog = new StLog();
        stLog.setId(UUID.randomUUID().toString());
        stLog.setUserName(user.getUserName());
        stLog.setIp(request.getRemoteAddr());
        stLog.setTime(new Date(System.currentTimeMillis()));
        stLog.setMethod(joinPoint.getSignature().getName());
        stLog.setAction(joinPoint.getTarget().getClass().getName());
        stLog.setCompanyId(user.getCompanyId());
        stLog.setCompanyName(user.getCompanyName());
        stLogService.save(stLog);
        // 执行目标方法
        Object result = joinPoint.proceed();
        return result;
    }
}